<template>
  <div class="vote-list">
    <el-card>
      <!-- 页面标题和操作按钮 -->
      <div class="page-header">
        <div class="header-left">
          <h2>投票管理</h2>
          <p class="description">管理用户投票数据，查看投票统计和趋势分析</p>
        </div>
        <div class="header-right">
          <el-button 
            v-if="userStore.hasPermission(ALL_PERMISSIONS.VOTE_READ)"
            type="primary" 
            @click="showStatistics"
          >
            <el-icon><DataAnalysis /></el-icon>
            投票统计
          </el-button>
          <el-button 
            v-if="userStore.hasPermission(ALL_PERMISSIONS.VOTE_RESET)"
            type="warning" 
            @click="resetVotes"
          >
            <el-icon><Refresh /></el-icon>
            重置投票
          </el-button>
        </div>
      </div>

      <!-- 统计信息 -->
      <el-descriptions title="实时统计" :column="4" border style="margin-bottom: 20px;">
        <el-descriptions-item label="总票数">{{ voteStats.overview?.totalVotes ?? 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="投票人数">{{ voteStats.overview?.totalVoters ?? 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="参与艺人">{{ voteStats.overview?.totalArtists ?? 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDate(voteStats.timestamp) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 热门艺人排行 -->
      <el-card v-if="voteStats.topArtists?.length" title="热门艺人排行" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col 
            v-for="(item, index) in voteStats.topArtists.slice(0, 4)" 
            :key="item.artistId" 
            :span="6"
          >
            <div class="artist-rank-card">
              <div class="rank-number" :class="`rank-${index + 1}`">{{ index + 1 }}</div>
              <el-avatar 
                :src="item.artist.avatar" 
                :size="60"
                :icon="UserFilled"
              />
              <div class="artist-info">
                <div class="artist-name">{{ item.artist.name }}</div>
                <div class="artist-genre">{{ item.artist.genre }}</div>
                <div class="vote-count">{{ item.totalVotes }} 票</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 每日投票趋势 -->
      <el-card v-if="voteStats.dailyVotes?.length" title="每日投票趋势" style="margin-bottom: 20px;">
        <div class="daily-votes-chart">
          <div 
            v-for="item in voteStats.dailyVotes.slice(-7)" 
            :key="item.date" 
            class="daily-vote-item"
          >
            <div class="vote-bar" :style="{ height: `${(item.votes / Math.max(...voteStats.dailyVotes.map(d => d.votes))) * 100}%` }"></div>
            <div class="vote-date">{{ formatDate(item.date, 'MM-DD') }}</div>
            <div class="vote-count">{{ item.votes }}</div>
          </div>
        </div>
      </el-card>

      <!-- 活跃投票用户 -->
      <el-card v-if="voteStats.topVoters?.length" title="活跃投票用户" style="margin-bottom: 20px;">
        <el-table :data="voteStats.topVoters" stripe>
          <el-table-column label="排名" width="80">
            <template #default="{ $index }">
              <div class="rank-badge" :class="`rank-${$index + 1}`">{{ $index + 1 }}</div>
            </template>
          </el-table-column>
          <el-table-column label="用户" width="200">
            <template #default="{ row }">
              <div class="user-info">
                <el-avatar :size="40" :icon="UserFilled" />
                <div class="user-details">
                  <div class="username">{{ row.user?.username }}</div>
                  <div class="real-name">{{ row.user?.realName || '未设置姓名' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="totalVotes" label="投票次数" width="120">
            <template #default="{ row }">
              <el-tag type="success" size="large">{{ row.totalVotes }} 次</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 搜索和筛选 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="艺人">
            <el-select v-model="searchForm.artistId" placeholder="选择艺人" clearable filterable>
              <el-option
                v-for="artist in artistList"
                :key="artist.id"
                :label="artist.name"
                :value="artist.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="用户">
            <el-input
              v-model="searchForm.userId"
              placeholder="输入用户ID"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 投票列表 -->
      <el-table
        v-loading="loading"
        :data="voteList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="用户" width="150">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="30" :icon="UserFilled" />
              <div class="user-details">
                <div class="username">{{ row.user?.username }}</div>
                <div class="real-name">{{ row.user?.realName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="艺人" width="150">
          <template #default="{ row }">
            <div class="artist-info">
              <el-avatar 
                :src="row.artist?.avatar" 
                :size="30"
                :icon="UserFilled"
              />
              <span class="artist-name">{{ row.artist?.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="投票时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="userStore.hasPermission(ALL_PERMISSIONS.VOTE_DELETE)"
              size="small" 
              type="danger" 
              @click="deleteVote(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
                  :current-page="pagination.page"
        :page-size="pagination.limit"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DataAnalysis, Refresh, UserFilled } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { voteApi, artistApi } from '@/api'
import { ALL_PERMISSIONS } from '@/constants/permissions'
import type { Vote, Artist } from '@/types'
import { formatDate } from '@/utils/format'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const voteList = ref<Vote[]>([])
const artistList = ref<Artist[]>([])
const voteStats = ref<any>({})
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0
})

const searchForm = reactive({
  artistId: '',
  userId: ''
})

// 获取投票列表
const fetchVotes = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      limit: pagination.limit,
      artistId: Number(searchForm.artistId),
      userId: Number(searchForm.userId)
    }
    const response = await voteApi.getList(params)
    voteList.value = response.data.data
    pagination.total = response.data.pagination.total
    pagination.page = response.data.pagination.page
    pagination.limit = response.data.pagination.limit
  } catch (error) {
    ElMessage.error('获取投票列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchVotes()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    artistId: '',
    userId: ''
  })
  handleSearch()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.limit = size
  pagination.page = 1
  fetchVotes()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchVotes()
}

// 显示统计对话框
const showStatistics = async () => {
  try {
    await fetchVoteStats()
    ElMessage.success('统计数据已更新')
  } catch (error) {
    ElMessage.error('更新统计数据失败')
  }
}

// 重置投票数据
const resetVotes = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要重置所有投票数据吗？此操作不可恢复。',
      '确认重置',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await voteApi.reset()
    ElMessage.success('投票数据重置成功')
    fetchVotes()
    fetchVoteStats()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('重置失败')
    }
  }
}

// 删除投票记录
const deleteVote = async (vote: Vote) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条投票记录吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await voteApi.delete(vote.id)
    ElMessage.success('删除成功')
    fetchVotes()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取艺人列表
const fetchArtists = async () => {
  try {
    const response = await artistApi.getList({ limit: 1000 }) // 获取所有艺人用于筛选
    artistList.value = response.data.data
  } catch (error) {
    ElMessage.error('获取艺人列表失败')
  }
}

// 获取投票统计
const fetchVoteStats = async () => {
  try {
    const response = await voteApi.getStatistics()
    voteStats.value = response.data
  } catch (error) {
    ElMessage.error('获取投票统计失败')
  }
}

// 初始化
onMounted(() => {
  fetchVotes()
  fetchArtists()
  fetchVoteStats()
})
</script>

<style scoped>
.vote-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: right;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
}

.username {
  font-size: 14px;
  color: #303133;
}

.real-name {
  font-size: 12px;
  color: #909399;
}

.artist-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.artist-name {
  font-size: 14px;
  color: #303133;
}

/* 新增统计组件样式 */
.artist-rank-card {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  position: relative;
  transition: transform 0.3s ease;
}

.artist-rank-card:hover {
  transform: translateY(-5px);
}

.rank-number {
  position: absolute;
  top: -10px;
  left: -10px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 16px;
}

.rank-1 {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
}

.rank-2 {
  background: linear-gradient(135deg, #c0c0c0 0%, #e5e5e5 100%);
}

.rank-3 {
  background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
}

.rank-4 {
  background: linear-gradient(135deg, #4a90e2 0%, #7bb3f0 100%);
}

.artist-rank-card .artist-info {
  margin-top: 15px;
}

.artist-rank-card .artist-name {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.artist-genre {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
}

.artist-rank-card .vote-count {
  font-size: 14px;
  color: #409eff;
  font-weight: bold;
}

.daily-votes-chart {
  display: flex;
  align-items: flex-end;
  gap: 20px;
  height: 200px;
  padding: 20px 0;
}

.daily-vote-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.vote-bar {
  width: 30px;
  background: linear-gradient(to top, #409eff, #67c23a);
  border-radius: 4px 4px 0 0;
  min-height: 20px;
  transition: all 0.3s ease;
}

.vote-date {
  font-size: 12px;
  color: #606266;
}

.vote-count {
  font-size: 14px;
  color: #303133;
  font-weight: bold;
}

.rank-badge {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  color: white;
  font-size: 12px;
  margin: 0 auto;
}

.rank-badge.rank-1 {
  background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
}

.rank-badge.rank-2 {
  background: linear-gradient(135deg, #c0c0c0 0%, #e5e5e5 100%);
}

.rank-badge.rank-3 {
  background: linear-gradient(135deg, #cd7f32 0%, #daa520 100%);
}
</style>